package com.toman.ui.my;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.ProgressDialogUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.camera.Camera;
import com.toman.toolbar.ToolBarWhiteActivity;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class FeedBackActivity extends ToolBarWhiteActivity {
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv_count)
    TextView tvCount;
    @BindView(R.id.btn_ok)
    Button btnOk;
    private Camera camera;
    Dialog dialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back);
        ButterKnife.bind(this);
        initView();
        initToolBar("", getResources().getColor(R.color.white));
        initHandler();
    }

    private void initView() {
        camera = ViewUtil.createPhoto("请提供相关问题的截图或照片", camera, this, ll);
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //TODO:
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
tvCount.setText("剩余"+(100-etContent.getText().toString().length())+"字");

            }

            @Override
            public void afterTextChanged(Editable s) {
                //TODO:
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick(R.id.btn_ok)
    public void onViewClicked() {
        add();
    }

    private void initHandler() {
        mHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {

                    case 1:
                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);
                        finish();
                        break;
                    case 2:

                        ToastUtil.makeText(getApplicationContext(), (String) msg.obj);

                        break;
                    default:
                        break;
                }
            }
        };
    }

    public void add() {
        if (etContent.getText().toString().equals("")) {
            ToastUtil.makeText(getApplicationContext(), "请输入反馈内容");
            return;
        }

        List<String> list = camera.getCompressUrl();
        Map<String, String> map = new HashMap<String, String>();
        map.put("describe", etContent.getText().toString());
        map.put("token", token);
        dialog = ProgressDialogUtils.showProgressDialog(this, "正在上传中", "请稍后");
        upload((HashMap<String, String>) map, list);
    }

    private void upload(HashMap<String, String> map, List<String> paths) {
        final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
        //创建OkHttpClient实例
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();
        MultipartBody.Builder mbody = new MultipartBody.Builder().setType(MultipartBody.FORM);

//遍历map中所有参数到builder
        for (String key : map.keySet()) {
            mbody.addFormDataPart(key, map.get(key));
        }


        for (String path : paths) {
            File file = new File(path);
            if (file.exists()) {
                mbody.addFormDataPart("file", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            }
            // builder.addFormDataPart("file[]", null, RequestBody.create(MEDIA_TYPE_PNG, new File(path)));
        }


        //构建请求体
        RequestBody requestBody = mbody.build();
        final Request request = new Request.Builder()
                .header("Authorization", "Client-ID " + "...")

                .url(NewBaseUrl.suggestion_save)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                dialog.dismiss();

                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.i("test", "意见反馈: " + result);
                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                if (code == 0) {
                    dialog.dismiss();

                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                } else {
                    dialog.dismiss();

                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = jsonObj.getString("msg");//可以是基本类型，可以是对象，可以是List、map等；
                    mHandler.sendMessage(msg);
                }
            }
        });


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dialog!=null)
        {  dialog.dismiss();}

    }
}
